
#include <stdio.h>
#include <stdlib.h>

#include "itemslist.h"
#include "../common/mem.h"

void itemslist__file_error(const char* msg)
{
	printf("%s\n", msg);
	exit(-1);
}

ItemsListItem* itemslist__new_item(ItemsListItemType value)
{
	ItemsListItem* new_item;
	new_item = (ItemsListItem*) mem_alloc(1, sizeof(ItemsListItem));
	itemslist__init_item(new_item, value);
	return new_item;
}

void itemslist__init_item(ItemsListItem* item, ItemsListItemType value)
{
	item->next = 0;
	item->value = value;
}

ItemsList itemslist__read_list_from_file(const char* filename)
{
	FILE* file;
	ItemsList result;

	itemslist__init(&result);

	file = fopen(filename, "r");
	if (!file)
	{
		itemslist__file_error("Error opening vector file!");
		return result;
	}

	result = itemslist__read_list_from_filestream(file);
	fclose(file);
	return result;
}

ItemsListItemType* itemslist__to_array(ItemsList vector)
{
	ItemsListItemType* result;
	int i;
	ItemsListItem* vector_item;

	result = mem_alloc_and_zero(vector.count, sizeof(ItemsListItemType));

	vector_item = vector.head;
	for (i = 0; i < vector.count; i++)
	{
		result[i] = vector_item->value;
		vector_item = vector_item->next;
	}

	return result;
}

ItemsList itemslist__read_list_from_filestream(FILE* file)
{
	ItemsListItemType item_value;
	int read_count;
	ItemsList result;

	itemslist__init(&result);

	read_count = fscanf(file, ItemsListItemScanFormat, &item_value);
	while (read_count == 1)
	{
		itemslist__add_item_to_list(item_value, &result);
		read_count = fscanf(file, ItemsListItemScanFormat, &item_value);
	}

	return result;
}

void itemslist__delete_vector(ItemsList vector)
{
	ItemsListItem* next;
	ItemsListItem* vector_item;

	vector_item = vector.head;
	while (vector_item)
	{
		next = vector_item->next;
		mem_free(vector_item);
		vector_item = next;
	}
}

void itemslist__add_item_to_list(ItemsListItemType item, ItemsList* list)
{
	ItemsListItem* new_item;

	new_item = itemslist__new_item(item);

	if (list->tail != 0)
		list->tail->next = new_item;
	else /*  This is an empty list, link as head */
		list->head = new_item;

	list->tail = new_item;
	list->count++;
}

void itemslist__init(ItemsList* list)
{
	list->count = 0;
	list->head = 0;
	list->tail = 0;
}